package ua.pp.bizon.main;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        List<File> list = loadFilesList();
        for (File f : list) {
            backup(f);
        }
    }

    private static void backup(File f) {
        if (f.length() > Integer.MAX_VALUE){
            throw new RuntimeException("files bigger than 2Gb is not supported");
        }
        char[] array = new char[(int) (f.length())];
        try {
            FileReader reader = new FileReader(f);
            reader.read(array);
            char[] encoded = encode(array);
            check(f, array, encoded);
        } catch (Exception e) {
            System.err.println(e);
        }
    }

    private static void check(File f, char[] array, char[] encoded) {
        char[] decoded = decode(encoded);
        if (!Arrays.equals(decoded, array)) {
            int pos = equals(decoded, array);
            System.out.println("pos:" + pos);
            char from = array[pos];
            System.out.println("form:" + (int) from);
            throw new RuntimeException("error in encoding file: " + f
                    + " on pos: " + equals(decoded, array) + " datas:"
                    + ((int) decoded[pos]) + ":" + ((int) from) + ":");

        }
    }

    public static int equals(char[] a, char[] a2) {
        if (a == a2)
            return 0;
        if (a == null || a2 == null)
            return 0;

        int length = a.length;
        if (a2.length != length)
            return -1;

        for (int i = 0; i < length; i++)
            if (a[i] != a2[i])
                return i;

        return 0;
    }

    private static final char[] key;
    static {
        File privatefile = new File("key.private");
        if (!privatefile.exists()) {
            privatefile = new File("src/main/resources/key.private");
        }
        key = new char[(int) privatefile.length() - 1];
        try {
            FileReader reader = new FileReader(privatefile);
            reader.read(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static char[] decode(char[] encoded) {
        char[] rezult = new char[encoded.length];
        int keystep = 0;
        for (int step = 0; step < encoded.length; step++) {
            rezult[step] = (char) (encoded[step] ^ key[keystep]);
            keystep = (keystep == key.length - 1 ? 0 : keystep + 1);
        }
        return rezult;
    }

    static char[] encode(char[] array) {
        return decode(array);
    }

    private static List<File> loadFilesList() {
        List<File> list = new ArrayList<File>();
        list.add(new File("/Users/roman/Downloads/linkedin error.JPG"));
        return list;
    }

}
